package com.ambitor.ipro.app.count;

import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.util.TableName;

public class CountDaySum {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private SuperDao dao = null;

	private String clctStart;

	private String clctEnd;

	public CountDaySum(Connection conn, Date clctDate) {
		dao = new SuperDaoImpl(conn);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		clctStart = sdf.format(clctDate);
		sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		clctEnd = sdf.format(clctDate);
	}

	@SuppressWarnings("unchecked")
	public void parseRefererAndSum() throws Exception {
		parseReferer();
	}

	@SuppressWarnings("unchecked")
	private void parseReferer() throws Exception {
		IDataset dataset = fetchNotDealedPv();
		while (dataset.size() > 0) {
			for (int i = 0; i < dataset.size(); i++) {
				IData pvMap = dataset.getData(i);
				String url = pvMap.getString("URL");
				String iid = parseUrlAndGetIid(url);
				pvMap.put("IID", iid);
				String fromIid = parseUrlAndGetFromIid(url);
				pvMap.put("FROM_IID", fromIid);
				pvMap.put("DEAL_TAG", "1");
				pvMap.remove("URL");
			}
			try {
				dao.update(TableName.TL_S_PV, dataset);
			} catch (Exception e) {
				logger.error("保存parseReferer数据失败", e);
				return;
			}
			dataset = fetchNotDealedPv();
		}
	}

	@SuppressWarnings("unchecked")
	private IDataset fetchNotDealedPv() {
		int batchNum = Integer.parseInt(CountPropertiesReader
				.getString("BATCH_PV_NUM"));
		String sql = "(select pv_id,url from "
				+ TableName.TL_S_PV
				+ " where "
				+ " visit_time between :CLCT_DAY_START and :CLCT_DAY_END and deal_tag = 0 limit :BATCH_NUM)";
		IData param = new DataMap();
		param.put("CLCT_DAY_START", clctStart);
		param.put("CLCT_DAY_END", clctEnd);
		param.put("BATCH_NUM", batchNum);
		IDataset dataset = null;
		try {
			dataset = dao.queryListBySql(sql, param);
		} catch (Exception e) {
			logger.error("查询当天新增pv数据失败", e);
		}
		return dataset;
	}

	/*
	@SuppressWarnings("unchecked")
	private void sumIidTotalDay() {
		IData param = new DataMap();
		param.put("CLCT_DAY_START", clctStart);
		param.put("CLCT_DAY_END", clctEnd);
		String sql = "select user_id,"
				+ clctDay
				+ " stat_date,iid,count(ip) pageview,count(distinct ip) userview from "
				+ TableName.TL_S_PV
				+ " where visit_time between :CLCT_DAY_START and :CLCT_DAY_END and iid is not null and iid <> '' group by user_id,iid";
		IDataset dataset = null;
		try {
			dataset = dao.queryListBySql(sql, param);
		} catch (Exception e) {
			logger.error("获取处理过的iid_total_sum_day失败", e);
			return;
		}

		try {
			dao.insert(TableName.TF_S_PV_TOTAL_DAY, dataset);
		} catch (Exception e) {
			logger.error("insert处理过的iid_total_sum_day失败", e);
			return;
		}
	}

	@SuppressWarnings("unchecked")
	private void sumIidProDay() {
		IData param = new DataMap();
		param.put("CLCT_DAY_START", clctStart);
		param.put("CLCT_DAY_END", clctEnd);
		String sql = "select user_id,"
				+ clctDay
				+ " stat_date,iid,from_iid,count(ip) pageview,count(distinct ip) userview from "
				+ TableName.TL_S_PV
				+ " where visit_time between :CLCT_DAY_START and :CLCT_DAY_END"
				+ " and from_iid is not null and from_iid <> '' group by user_id,iid,from_iid";
		IDataset dataset = null;
		try {
			dataset = dao.queryListBySql(sql, param);
		} catch (Exception e) {
			logger.error("获取处理过的iid_pro_sum_day失败", e);
			return;
		}

		try {
			dao.insert(TableName.TF_S_PV_PRO_DAY, dataset);
		} catch (Exception e) {
			logger.error("insert处理过的iid_pro_sum_day失败", e);
			return;
		}

	}
	*/
	private String parseUrlAndGetIid(String url) {
		String iid = "";
		String regex = "id=[\\d]{10,15}";
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(url);
		if (m.find()) {
			iid = m.group();
			iid = iid.replace("id=", StringUtils.EMPTY);
		}
		return StringUtils.trimToEmpty(iid);
	}

	private String parseUrlAndGetFromIid(String url) {
		String iid = "";
		String regex = "from_id=[\\d]{10,15}";
		Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(url);
		if (m.find()) {
			iid = m.group();
			iid = iid.replace("from_id=", StringUtils.EMPTY);
		}
		return StringUtils.trimToEmpty(iid);
	}
}
